package com.kgc.sportscircle.filter;

import com.kgc.sportscircle.pojo.Sportsuser;
import com.kgc.sportscircle.redis.LoginPrefix;
import com.kgc.sportscircle.redis.RedisService;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginFilter" ,urlPatterns = "/page/front_page/mall/mall_cart.html")
public class UrlFilter implements Filter {
    @Resource
    private RedisService redisService;


    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
       Cookie[] cookies = request.getCookies();
       String token = null;
        for (Cookie cookie:cookies) {
            if (cookie.getName().equals("token")){
                token=cookie.getValue();
            }
        }

        //本地没有token或者redis里查不到，返回登陆页面
        if (token==null||redisService.get(LoginPrefix.getLoginList,token, Sportsuser.class)==null){
            response.sendRedirect(request.getContextPath()+"/page/front_page/admin/login.htm");
        }
        System.out.println(request.getContextPath());
        filterChain.doFilter(request,response);
    }

    public void destroy() {

    }
}
